package com.mingtu.dzpatrol.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Base64;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.core.util.Pair;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.blankj.utilcode.util.EncodeUtils;
import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.base.BaseApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @ClassName :
 * @Author : wkk
 * @Date : 2020/8/17 10:35:23
 * @Email : 1281573890@qq.com
 * @Eescription :
 */
public class MyUtills {
    public static Context context = BaseApplication.getContext();

    public static void setTextViewColor(TextView view) {
        view.setTextColor(context.getResources().getColor(R.color.text_color333));
    }

    public static void setEditTextColor(EditText view) {
        view.setTextColor(context.getResources().getColor(R.color.text_color333));
    }

    public static String getTextView(TextView view) {
        return view.getText().toString().trim();
    }

    public static String getEditText(EditText view) {
        return view.getText().toString().trim();
    }

    /**
     * 格式化秒数
     *
     * @param seconds
     * @return
     */
    public static String formatSeconds(long seconds) {
//        String standardTime;
//        if (seconds <= 0) {
//            standardTime = "00h : 00m : 00s";
//        } else if (seconds < 60) {
//            standardTime = String.format(Locale.getDefault(), "00h : 00m : %02ds", seconds % 60);
//        } else if (seconds < 3600) {
//            standardTime = String.format(Locale.getDefault(), "00h : %02dm : %02ds", seconds / 60, seconds % 60);
//        } else {
//            standardTime = String.format(Locale.getDefault(), "%02dh : %02dm : %02ds", seconds / 3600, seconds % 3600 / 60, seconds % 60);
//        }
//        return standardTime;

        String standardTime;
        int duration = Integer.parseInt(String.valueOf(seconds));
        DecimalFormat df = new DecimalFormat("0.00");
        standardTime = df.format((float) duration / 3600) + "";//取出小时
        return standardTime + "h";
    }

    /**
     * 格式化秒数
     *
     * @param seconds
     * @return
     */
    public static String formatSeconds2(long seconds) {
        String standardTime;
//        if (seconds <= 0) {
//            standardTime = 0+"";
//        } else if (seconds < 60) {
//            standardTime = seconds+"";
//        } else {
        int duration = Integer.parseInt(String.valueOf(seconds));
        DecimalFormat df = new DecimalFormat("0.00");
        standardTime = df.format((float) duration / 3600) + "";//取出小时
//        }
        return standardTime;
    }


    /**
     * 格式化秒数
     *
     * @param seconds
     * @return
     */
    public static String formatSeconds3(long seconds) {
        String standardTime;
        if (seconds <= 0) {
            standardTime = "00h : 00m : 00s";
        } else if (seconds < 60) {
            standardTime = String.format(Locale.getDefault(), "00h : 00m : %02ds", seconds % 60);
        } else if (seconds < 3600) {
            standardTime = String.format(Locale.getDefault(), "00h : %02dm : %02ds", seconds / 60, seconds % 60);
        } else {
            standardTime = String.format(Locale.getDefault(), "%02dh : %02dm : %02ds", seconds / 3600, seconds % 3600 / 60, seconds % 60);
        }
        return standardTime;
    }

    /**
     * 格式化秒数
     *
     * @param seconds
     * @return
     */
    public static String formatSeconds4(long seconds) {
        String standardTime;
        if (seconds <= 0) {
            standardTime = "00:00";
        } else if (seconds < 60) {
            standardTime = String.format(Locale.getDefault(), " 00:%02d", seconds % 60);
        } else if (seconds < 3600) {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d", seconds / 60, seconds % 60);
        } else {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d:%02d", seconds / 3600, seconds % 3600 / 60, seconds % 60);
        }
        return standardTime;
    }


    /**
     * 格式化秒数
     *
     * @param seconds
     * @return
     */
    public static String formatSeconds5(long seconds) {
        String standardTime;
        if (seconds <= 0) {
            standardTime = 0 + "s";
        } else if (seconds < 60) {
            standardTime = seconds + "s";
        } else {
            int duration = Integer.parseInt(String.valueOf(seconds));
            DecimalFormat df = new DecimalFormat("0.00");
            standardTime = df.format((float) duration / 3600) + "h";//取出小时
        }
        return standardTime;
    }

    /**
     * 分页加载的页码
     *
     * @param list
     * @param eachPageNum
     * @param <T>
     * @return
     */
    public static <T> int loadPage(List<T> list, int eachPageNum) {
        MyLogUtil.e("loadPage ", "list.size()==" + list.size());
        MyLogUtil.e("loadPage ", "eachPageNum==" + eachPageNum);
        MyLogUtil.e("loadPage ", "page==" + Math.floor(list.size() / eachPageNum) + 1);
        return (int) (Math.floor(list.size() / eachPageNum) + 1);
    }


    /**
     * File 文件转Base64
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(File file) throws Exception {
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }


    /**
     * 将时间戳转换为时间
     */
    public static String stampToDateTime(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static String stampToDateTime2(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }


    /**
     * 将一个InputStream流转换成字符串
     *
     * @param is
     * @return
     */
    public static String inputStreamToString(InputStream is) {
        StringBuffer res = new StringBuffer();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader read = new BufferedReader(isr);
        try {
            String line;
            line = read.readLine();
            while (line != null) {
                res.append(line + "");
                line = read.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != isr) {
                    isr.close();
                    isr.close();
                }
                if (null != read) {
                    read.close();
                    read = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
            }
        }
        return res.toString();
    }

    /**
     * 计算轨迹距离
     */
    public static float getDistance(List<LatLng> list) {
        float distance = 0;
        if (list == null || list.size() == 0) {
            return distance;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            LatLng firstLatLng = list.get(i);
            LatLng secondLatLng = list.get(i + 1);
            double betweenDis = AMapUtils.calculateLineDistance(firstLatLng,
                    secondLatLng);
            distance = (float) (distance + betweenDis);
        }
        return distance;
    }


    public static LatLngBounds getBounds(List<LatLng> pointlist) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (pointlist == null) {
            return b.build();
        }
        for (int i = 0; i < pointlist.size(); i++) {
            b.include(pointlist.get(i));
        }
        return b.build();

    }


    /**
     * 计算轨迹回放的时间
     */
    public static int getMoveTime(float distance) {
        int kilometre = 1000;
        int moveTime = 6; //秒
        if (distance < 5 * kilometre) {
            moveTime = 10;
        } else if (distance >= 5 * kilometre && distance < 10 * kilometre) {
            moveTime = 9;
        } else if (distance >= 10 * kilometre && distance < 15 * kilometre) {
            moveTime = 8;
        } else if (distance >= 15 * kilometre && distance < 20 * kilometre) {
            moveTime = 7;
        } else if (distance >= 20 * kilometre) {
            moveTime = 6;
        }
        return moveTime;
    }

    /**
     * 判断网络图片是否存在
     * posturl 图片地址链接
     */
    public static int isImagesTrue(String imgUrl) throws IOException {
        URL url = new URL(imgUrl);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setRequestMethod("GET");
        urlcon.setConnectTimeout(3000);
        urlcon.setReadTimeout(3000);
        urlcon.setRequestProperty("Content-type",
                "application/x-www-form-urlencoded");
        if (urlcon.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return 200;
        } else {
            return 404;
        }
    }

    public static RecyclerView.ItemDecoration getRecyclerViewDivider(Context context, @DrawableRes int drawableId) {
        DividerItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(context.getResources().getDrawable(drawableId));
        return itemDecoration;
    }

    /**
     * Drawable 转 Bitmap
     *
     * @param drawable Drawable
     * @return Bitmap
     */
    public static Bitmap drawable2Bitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }


    public static Pair<String, String> genKeyPair(int size) throws NoSuchAlgorithmException {

        if (size == 1024) {
            return Pair.create(
                    "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYHGvdORdwsK5i+s9rKaMPL1O5eDK2XwNHRUWaxmGB/cxLxeinJrrqdAN+mME7XtGN9bklnOR3MUBQLVnWIn/IU0pnIJY9DpPTVc7x+1zFb8UUq1N0BBo/NpUG5olxuQULuAAHZOg28pnP/Pcb5XVEvpNKL0HaWjN8pu/Dzf8gZwIDAQAB",
                    "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJgca905F3CwrmL6z2spow8vU7l4MrZfA0dFRZrGYYH9zEvF6Kcmuup0A36YwTte0Y31uSWc5HcxQFAtWdYif8hTSmcglj0Ok9NVzvH7XMVvxRSrU3QEGj82lQbmiXG5BQu4AAdk6Dbymc/89xvldUS+k0ovQdpaM3ym78PN/yBnAgMBAAECgYAFdX+pgNMGiFC53KZ1AhmIAfrPPTEUunQzqpjE5Tm6oJEkZwXiedFbeK5nbLQCnXSH07nBT9AjNvFH71i6BqLvT1l3/ezPq9pmRPriHfWQQ3/J3ASf1O9F9CkYbq/s/qqkXEFcl8PdYQV0xU/kS4jZPP+60Lv3sPkLg2DpkhM+AQJBANTl+/v6sBqqQSS0Anl5nE15Ck3XGBcq0nvATHfFkJYtG9rrXz3ZoRATLxF1iJYwGSAtirhev9W7qFayjci0ztcCQQC25/kkFbeMEWT6/kyV8wcPIog1mKy8RVB9+2l6C8AzbWBPZYtLlB7uaGSJeZBTEGfvRYzpFm5xO0JqwCfDddjxAkBmxtgM3wqg9MwaAeSn6/Nu2x4EUfBJTtzp7P19XJzeQsyNtM73ttYwQnKYhRr5FiMrC5FKTENj1QIBSJV17QNlAkAL5cUAAuWgl9UQuo/yxQ81fdKMYfUCfiPBPiRbSv5imf/Eyl8oOGdWrLW1d5HaxVttZgHHe60NcoRce0la3oSRAkAe8OqLsm9ryXNvBtZxSG+1JUvePVxpRSlJdZIAUKxN6XQE0S9aEe/IkNDBgVeiUEtop76R2NkkGtGTwzbzl0gm"
            );
        } else if (size == 2048) {
            return Pair.create(
                    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjLLeJZIO7dfQKb6tHE+TlhvD1m3UdTefKvl4uNQboDXy2ztgPcksjLDXxsT+znxMBh4RpXxfVPgnrcSLewGVhTb3uXh9sWo6tvvshNaMKBTebaZePhE7grq+LHH3NILscVssK24rDSvIquZ4nUbDipF/Iscge4LwnypcCuun/3RCn4HYzXW+0YFFZC8Vq4zabIxtzzkvgZlAlvuD6tT76Uuo5kD8b36yYNALI+ZStOj283wlL8PgyyitRGaqCH+MjWYqDb5C0DN31kcoSU7ARTGWgNNAoexAdNujkBvVRFyR2cH9FpjJDu18Oa8v9uSjlRftVWPj0OQXE7vRUsrrawIDAQAB",
                    "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCMst4lkg7t19Apvq0cT5OWG8PWbdR1N58q+Xi41BugNfLbO2A9ySyMsNfGxP7OfEwGHhGlfF9U+CetxIt7AZWFNve5eH2xajq2++yE1owoFN5tpl4+ETuCur4scfc0guxxWywrbisNK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gAa+hMJueDmr0gkRQKBgDKhd1Rwxvd4Y1ZejxVI43SmFOzt2t98JGFgXHLnFmdtFWNLJlNC3EhXx99Of+gwH9OIFxljeRxhXuTgFfwcXT+AceTdplExrBuvr/qJbDK7hNsu/oDBBCjlyu/BQQc4CZEtCOJZjJTNGF5avWjrh/urd1nITosPZV6fIdhl86pFAoGAfOwK0Wte6gO5glAHP9RNktDeyFJCfFH1KUFiAG7XUww6bRpL2fEAqBIcDVgsS565ihxDSbUjgQgg/Ckh2+iBrwf1K9ViO4XUuwWqRS26rn4Is/W5kbPtnC4HS5cQIH1aWi3xUMJcWxV4ZrwiMVdw91leYWC0IbXC/yrc/PBW+sE="
            );
        }

        SecureRandom secureRandom = new SecureRandom();

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        keyPairGenerator.initialize(size, secureRandom);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        Key publicKey = keyPair.getPublic();

        Key privateKey = keyPair.getPrivate();

        byte[] publicKeyBytes = publicKey.getEncoded();
        byte[] privateKeyBytes = privateKey.getEncoded();

        String publicKeyBase64 = EncodeUtils.base64Encode2String(publicKeyBytes);
        String privateKeyBase64 = EncodeUtils.base64Encode2String(privateKeyBytes);

        return Pair.create(publicKeyBase64, privateKeyBase64);
    }

}
